package br.ufc.great.dtx.tm.lm;

import java.io.Serializable;
import java.util.Vector;

import br.ufc.great.dtx.server.config.Config;

/**
 * 
 * @author Leonardo Oliveira Moreira
 *
 * Classe que representa uma lista de bloqueios de um elemento XML
 */
public class LockTable implements Serializable {

	private Vector<LockTableItem> itens;
	
	public LockTable() {
		itens = new Vector<LockTableItem>();
	}
	
	public void add(String transactionId, String operationId, long oid, int lock) throws LockIncompatibleException {
		synchronized (itens) {
			for (int i = 0; itens != null && i < itens.size(); i++) {
				LockTableItem item = itens.elementAt(i);
				if (item.getTransactionId().equalsIgnoreCase(transactionId) && /*item.getOperationId().equalsIgnoreCase(operationId) &&*/ oid == item.getOID() && item.getLockType() == lock)
					return;
				else
					if (! item.getTransactionId().equalsIgnoreCase(transactionId) && oid == item.getOID() && ! XDGLLockCompatibility.isCompatibility(item.getLockType(), lock)) {
						throw new LockIncompatibleException(item.getTransactionId());
					}
			}
			itens.add(new LockTableItem(transactionId, operationId, oid, lock));
		}
	}

	public boolean remove(String transactionId, int lock) {
		synchronized (itens) {
			for (int i = 0; itens != null && i < itens.size(); i++) {
				LockTableItem item = itens.elementAt(i);
				if (item.getTransactionId().equalsIgnoreCase(transactionId) && item.getLockType() == lock) {
					itens.removeElementAt(i);
					return true;
				}
			}
			return false;
		}
	}
	
	public void remove(String transactionId) {
		synchronized (itens) {
			for (int i = 0; itens != null && i < itens.size(); i++) {
				LockTableItem item = itens.elementAt(i);
				if (item.getTransactionId().equalsIgnoreCase(transactionId)) {
					itens.removeElementAt(i);
					i--;
				}
			}
		}
	}
	
	public void remove(String transactionId, String operationId) {
		synchronized (itens) {
			for (int i = 0; itens != null && i < itens.size(); i++) {
				LockTableItem item = itens.elementAt(i);
				if (item.getTransactionId().equalsIgnoreCase(transactionId) && item.getOperationId().equalsIgnoreCase(operationId)) {
					itens.removeElementAt(i);
					i--;
				}
			}
		}
	}
	
	public LockTableItem get(int index) {
		synchronized (itens) {
			return itens.elementAt(index);
		}
	}
	
	public int size() {
		synchronized (itens) {
			return itens.size();
		}
	}
	
}
